<?php

namespace server\trigger;

use server\SystemLogInterface;
use common\core\server\BaseEvent;
use common\core\server\BaseServer;
use common\core\server\BaseTrigger;
use common\core\server\TriggerInterface;
use server\UserInterface;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

class LoginTrigger extends BaseTrigger implements TriggerInterface
{

    public $log;

    public function __construct(SystemLogInterface $log, array $config = [])
    {
        $this->log = $log;
        parent::__construct($config);
    }

    /**
     * 绑定事件名称
     * @return string
     */
    public static function name()
    {
        return UserInterface::EVENT_USER_LOGIN_LOG;
    }

    /**
     * 执行
     *
     * @param BaseEvent $event
     *
     * @return mixed
     */
    public function run(BaseEvent $event)
    {
        $user = \Yii::$app->user->identity;
        $data = [
            'username'   => ArrayHelper::getValue($user, 'username', '未知用户'),
            'user_id'    => ArrayHelper::getValue($user, 'id',   '-3'),
            'ip'         => \Yii::$app->request->getUserIP(),
            'type'       => $event->params,
            'app_id'     => \Yii::$app->id,
            'created_at' => time(),
        ];
        $this->log->setUserLoginLog($data);
    }
}
